package org.divineryang.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import org.divineryang.mapper.CategoryMapper;
import org.divineryang.model.vo.product.CategoryExcelVo;

import java.util.List;

/**
 * @program new-bee
 * @Description
 * @Author Diviner Yang
 * @Date 2024/04/23 14:01
 * @Version 1.0
 */
public class ExcelListener <T> extends AnalysisEventListener<T> {

    //缓存的数据 100条
    private static final int BATCH_COUNT = 100;
    private List cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    //获取mapper对象
    private CategoryMapper categoryMapper;
    public ExcelListener(CategoryMapper categoryMapper) {
        this.categoryMapper = categoryMapper;
    }

    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        CategoryExcelVo categoryExcelVo =(CategoryExcelVo)t;
        cachedDataList.add(categoryExcelVo);
        //当数据到达100条批量插入数据库
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // excel解析完毕以后需要执行的代码这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
    }

    private void saveData() {
        categoryMapper.batchInsert(cachedDataList);
    }

}
